const Router = require('koa-router');
const mysql = require('mysql2/promise');
const bodyParser = require('koa-bodyparser');
const router = new Router();

router.use(bodyParser());

// 定义数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'student',
};

// 定义用户数据数组
let users = [];

// 获取用户数据的函数
async function getUsersFromDatabase() {
  try {
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);

    // 查询stu_user表中的数据
    const [rows] = await connection.execute("SELECT * FROM stu_user");

    // 将查询结果替换掉原来的users数组
    users = rows.map((row) => ({
      id: row.user_id,
      name: row.user_name,
      age: row.user_age,
      email: row.user_email,
      country: row.user_country,
      occupation: row.user_occupation,
      interests: row.user_interests,
    }));

    // 关闭数据库连接
    await connection.end();
  } catch (error) {
    console.error(error);
  }
}

// 初始化用户数据
getUsersFromDatabase();

// 查询用户列表
router.get('/user-list', async (ctx) => {
  try {
    // 返回查询结果
    ctx.body = {
      data: users,
      code: 200,
      message: '查询成功',
    };
  } catch (error) {
    console.error('Failed to query:', error);
    ctx.status = 500;
    ctx.body = { error: '内部服务器错误' };
  }
});

// 删除用户
router.delete("/delete-user/:id", async (ctx) => {
  const userId = parseInt(ctx.params.id);
  const userToDelete = users.find((user) => user.id === userId);

  if (!userToDelete) {
    ctx.status = 404;
    ctx.body = { error: "用户不存在" };
    return;
  }

  try {
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);

    // 从数据库中删除对应的用户信息
    await connection.execute("DELETE FROM stu_user WHERE user_id = ?", [userId]);

    // 关闭数据库连接
    await connection.end();
  } catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { code:500,error: "数据库操作失败" };
    return;
  }

  // 更新内存中的用户列表
  users = users.filter((user) => user.id !== userId);
  ctx.body = { code:200,message: "删除成功" };
});

module.exports = router;
